from rest_framework import serializers
from .models import City, Room, Device
        

class CitySerializer(serializers.ModelSerializer):
    name = serializers.CharField(error_messages={'错误': '城市不能为空'})

    class Meta:
        model = City
        fields = '__all__'

    def validate_name(self, value):
        # 检查城市名称是否已存在
        if City.objects.filter(name=value).exists():
            raise serializers.ValidationError("城市已存在，请勿重复添加")
        return value

class RoomSerializer(serializers.ModelSerializer):
    name = serializers.CharField(error_messages={'错误': '机房不能为空'})

    class Meta:
        model = Room
        fields = '__all__'

    def validate(self, attrs):
        if attrs["city"].room.filter(name=attrs["name"]).exists():
            raise serializers.ValidationError("机房已存在，请勿重复添加")
        return super().validate(attrs)

class DeviceSerializer(serializers.ModelSerializer):
    name = serializers.CharField(error_messages={'错误': '设备名称不能为空'})
    ip = serializers.CharField(error_messages={'错误': '设备ip不能为空'})

    class Meta:
        model = Device
        fields = '__all__'

    